package ca.liu.study.springdata.jpa.repository;

import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Named;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ca.liu.study.springdata.jpa.domain.Course;
import ca.liu.study.springdata.jpa.domain.Student;
import ca.liu.study.springdata.jpa.domain.Teacher;

@Named
public class EntityLoader {
	private static final Logger LOG = LoggerFactory.getLogger(EntityLoader.class);
	
	public static Student student1 = new Student("Jack", "Jones", "jack.jones@gmail.com");
	public static Student student2 = new Student("Liu", "Yang", "liuyang.ca@gmail.com");
	public static Student student3 = new Student("Tony", "Xu", "tony.xu@gmail.com");
	
	public static Course course1 = new Course("CSCI-116 Intro to C++");
	public static Course course2 = new Course("CSCI-338 Hardcore Java");
	
	public static Teacher teacher1 = new Teacher("Lawrence", "Yang", "lyang@stfx.ca");
	public static Teacher teacher2 = new Teacher("Man", "Lin", "mlin@stfx.ca");	
	
	@Inject private TeacherRepository teacherRepository;
	@Inject private StudentRepository studentRepository;
	@Inject private CourseRepository courseRepository;
	
	@PostConstruct
	void init() {
		LOG.debug("---------saving students and teachers.");
		saveStudentAndTeacher();
		saveCourse();
	}
	
	private void saveStudentAndTeacher() {
		studentRepository.save(EntityLoader.student1);
		studentRepository.save(EntityLoader.student2);
		studentRepository.save(EntityLoader.student3);
		
		teacherRepository.save(EntityLoader.teacher1);
		teacherRepository.save(EntityLoader.teacher2);
	}
	
	private void saveCourse() {		
		Teacher teacher1 = teacherRepository.findByEmail(EntityLoader.teacher1.getEmail());
		Teacher teacher2 = teacherRepository.findByEmail(EntityLoader.teacher2.getEmail());
		
		Student student1 = studentRepository.findByEmail(EntityLoader.student1.getEmail());
		Student student2 = studentRepository.findByEmail(EntityLoader.student2.getEmail());
		Student student3 = studentRepository.findByEmail(EntityLoader.student3.getEmail());
		
		EntityLoader.course1.setTeacher(teacher1);
		EntityLoader.course2.setTeacher(teacher2);
		
		EntityLoader.course1.getStudents().add(student1);
		EntityLoader.course1.getStudents().add(student3);
		EntityLoader.course2.getStudents().add(student2);
		EntityLoader.course2.getStudents().add(student3);
		
		
		courseRepository.save(EntityLoader.course1);
		courseRepository.save(EntityLoader.course2);
	}
}
